<template>
  <div>
    <!--    <div class="table-page-search-wrapper">-->
    <!--      <a-form-model :model="queryParam" layout="inline">-->
    <!--        <a-row :gutter="10">-->
    <!--          <a-col :md="6" :sm="24">-->
    <!--            <a-form-model-item label="入职时间">-->
    <!--              <a-range-picker @change="onChange" />-->
    <!--            </a-form-model-item>-->
    <!--          </a-col>-->
    <!--          <a-col :md="6" :sm="24">-->
    <!--              <span class="table-page-search-submitButtons">-->
    <!--                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>-->
    <!--              </span>-->
    <!--          </a-col>-->
    <!--        </a-row>-->
    <!--      </a-form-model>-->
    <!--    </div>-->
    <div style="margin-bottom: 16px">
      <a-button :disabled="selectedRowKeys.length == 0" size="small" type="primary" @click="batchSet">批量设置</a-button>
      <span style="margin-left: 8px">
          <template v-if="selectedRowKeys.length != 0">
            {{ `已选中 ${selectedRowKeys.length} 个顾问` }}
          </template>
        </span>
    </div>
    <s-table
      ref="table"
      :rowKey="(record) => record.uid"
      :columns="incColumns"
      :row-selection="rowSelection"
      :data="incData"
    >
      <div
        slot="filterSelect"
        slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
        style="padding: 8px"
      >
        <a-select
          show-search
          :placeholder="`选择${column.title}`"
          style="width: 188px; margin-bottom: 8px; display: block;"
          :value="selectedKeys[0]"
          :filter-option="filterOption"
          @change="(value) => setSelectedKeys(value ? [value] : [])"
          @pressEnter="() => handleSelect(selectedKeys, confirm, column.dataIndex)"
        >
          <a-select-option v-for="(item,index) in adviserOpts" :key="index" :value="index">{{item}}</a-select-option>
        </a-select>
        <a-button
          type="primary"
          icon="search"
          size="small"
          style="width: 90px; margin-right: 8px"
          @click="() => handleSelect(selectedKeys, confirm, column.dataIndex)"
        >
          搜索
        </a-button>
        <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters, column.dataIndex)">
          重置
        </a-button>
      </div>
      <div
        slot="filterRange"
        slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
        style="padding: 8px"
      >
        <a-range-picker
          style="width: 228px; margin-bottom: 8px; display: block;"
          :value="createValue"
          @change="onChange"
        />
        <a-button
          type="primary"
          icon="search"
          size="small"
          style="width: 110px; margin-right: 8px"
          @click="() => handleRange(selectedKeys, confirm, column.dataIndex)"
        >
          搜索
        </a-button>
        <a-button size="small" style="width: 110px" @click="() => rangeReset(clearFilters, column.dataIndex)">
          重置
        </a-button>
      </div>
      <template slot='group_type' slot-scope='text'>
        {{groupTypeOpts[text]}}
      </template>
      <template slot="username" slot-scope="text, record">
        <div v-html="record.username_format"></div>
      </template>
      <template slot="work_status" slot-scope="text, record">
        <a-button size="small" icon="edit" type="primary" @click="editStatus(record.uid, record.parent_id)">{{ workOpts[text] }}
        </a-button>
      </template>
      <template slot="status" slot-scope="text">
        <div>
          <a-tag v-if="text == 1" color="blue">正常</a-tag>
          <a-tag v-if="text == 0" color="red">禁用</a-tag>
        </div>
      </template>
      <template slot="target_currmonth_yj" slot-scope="text, record">
        <a-input v-if="record.lvl == 2" v-model="monthYjForm['yj' + record.uid]" style="width:100px" suffix="元" type="text"/>
      </template>
      <template slot="target_dacall_sc" slot-scope="text, record">
        <a-input v-if="record.lvl == 2" v-model="callForm['call' + record.uid]" style="width:100px" suffix="min" type="text"/>
      </template>
      <template slot="action" slot-scope="text, record">
        <a-button
          type="primary"
          size="small"
          :style="{ marginRight: '5px' }"
          @click="saveSetting(record.uid, record.resource_daily_num_limit, record.target_currmonth_yj, record.target_dacall_sc)"
        >
          保存设置
        </a-button>
        <a-button type="primary" size="small" @click="editMember(record.uid)">编辑</a-button>
      </template>
    </s-table>
    <a-modal
      title="编辑组员"
      v-model="editVisible"
      :width="600"
      @ok="onSubmit"
      @cancel="resetForm"
    >
      <a-form-model
        ref="editForm"
        :model="editForm"
        :rules="editRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="用户名" prop="username">
          <a-input type="text" v-model="editForm.username" placeholder="请输入用户名"/>
        </a-form-model-item>
        <a-form-model-item label="密码" prop="password">
          <a-input-password v-model="editForm.password" placeholder="请输入登陆密码"/>
        </a-form-model-item>
        <a-form-model-item label="登陆手机号" prop="login_phone">
          <a-input-password v-model="editForm.login_phone" placeholder="请输入登陆手机号"/>
        </a-form-model-item>
        <a-form-model-item label="选择顾问类型" prop="group_type">
          <a-select v-model="editForm.group_type" placeholder="选择顾问所属商标/专利/售后">
            <a-select-option v-for="(item,index) in groupTypeOpts" :key="index" :value="index">{{item}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="选择工作台" prop="group">
          <a-select v-model="editForm.group" placeholder="选择所属工作台">
            <a-select-option v-for="(item,index) in groupOpts" :key="index" :value="index">{{ item }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="选择所属上级" prop="parent_id">
          <a-select
            show-search
            v-model="editForm.parent_id"
            placeholder="选择所属上级"
            :filter-option="filterOption"
          >
            <a-select-option v-for="(item,index) in userOpts" :key="index" :value="index">{{item}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="用户状态" prop="status">
          <a-radio-group name="radioGroup" v-model="editForm.status">
            <a-radio v-for="(item, index) in statusOpts" :key="index" :value="index">
              {{ item }}
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="是否领取新资源" prop="is_can_receive">
          <a-radio-group name="radioGroup" v-model="editForm.is_can_receive">
            <a-radio v-for="(item,index) in ynOpts" :key="index" :value="index">
              {{ item }}
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="通时限制" prop="receive_is_need_ts">
          <a-radio-group name="radioGroup" v-model="editForm.receive_is_need_ts">
            <a-radio v-for="(item,index) in ynOpts" :key="index" :value="index">
              {{ item }}
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="添加微信限制" prop="receive_is_need_wx">
          <a-radio-group name="radioGroup" v-model="editForm.receive_is_need_wx">
            <a-radio v-for="(item,index) in ynOpts" :key="index" :value="index">
              {{ item }}
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="选择角色" prop="role">
          <a-select v-model="editForm.role" placeholder="选择所属上级">
            <a-select-option v-for="(item, index) in roleOpts" :key="index" :value="index">{{ item }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="考拉通讯账号">
          <a-input type="text" v-model="editForm.kaola_accounts" placeholder="输入考拉通信的账号"/>
        </a-form-model-item>
        <a-form-model-item label="南方电信账号">
          <a-input type="text" v-model="editForm.nanfang_accounts" placeholder="输入南方电信的账号"/>
        </a-form-model-item>
        <a-form-model-item label="云客账号">
          <a-input type="text" v-model="editForm.yunke_accounts" placeholder="输入云客的账号"/>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal
      title="编辑工作状态"
      v-model="statusVisible"
      :width="200"
      @ok="submitStatus"
    >
      <a-radio-group v-model="memberStatus">
        <a-radio v-for="(item, index) in memberStatusOpts" :key="index" :value="index">{{item}}</a-radio>
      </a-radio-group>
    </a-modal>
    <a-modal
      title="批量设置"
      v-model="batchVisible"
      :width="400"
      @ok="onBatch"
    >
      <a-form-model
        ref="batchForm"
        :model="batchForm"
        :rules="batchRules"
      >
        <a-form-model-item label="每天初始资源数" prop="resource_daily_num_limit">
          <a-input v-model="batchForm.resource_daily_num_limit" type="text"/>
        </a-form-model-item>
        <a-form-model-item label="本月业绩目标" prop="target_currmonth_yj">
          <a-input v-model="batchForm.target_currmonth_yj" type="text"/>
        </a-form-model-item>
        <a-form-model-item label="每天电话目标" prop="target_dacall_sc">
          <a-input v-model="batchForm.target_dacall_sc" type="text"/>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
  import { STable } from '@/components'
  import col from '@/columns/member'
  import {
    getEditMember, getMemberSetting,
    getMemberStatus,
    postEditMember,
    postMemberSetting,
    postMemberStatus,
    saveCall,
    saveMonthYj,
    saveResources,
    settingList
  } from '@/api/member'
  const incColumns = col.linc

  export default {
    components: {
      STable
    },
    name: 'LInc',
    data () {
      return {
        incColumns,
        incData: parameters => {
          return settingList(Object.assign(parameters, this.queryParam)).then(res => {
            this.statusOpts = res.result.status_opts
            this.workOpts = res.result.work_status_opts
            this.adviserOpts = res.result.adviser_array
            this.groupTypeOpts = res.result.group_type
            for (let i = 0; i < res.result.data.length; i++) {
              this.resourcesForm['num' + res.result.data[i].uid] = res.result.data[i].resource_daily_num_limit
              this.monthYjForm['yj' + res.result.data[i].uid] = res.result.data[i].target_currmonth_yj
              this.callForm['call' + res.result.data[i].uid] = res.result.data[i].target_dacall_sc
            }
            return res.result
          })
        },
        workOpts: {},
        queryParam: {},
        resourcesForm: {},
        monthYjForm: {},
        callForm: {},
        editVisible: false,
        editForm: {},
        groupOpts: {},
        roleOpts: {},
        userOpts: {},
        adviserOpts: {},
        ynOpts: {},
        statusOpts: {},
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
        editRules: {
          username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
          group: [{ required: true, message: '请选择工作组', trigger: 'change' }],
          group_type: [{ required: true, message: '请选择顾问所属类型', trigger: 'change' }],
          parent_id: [{ required: true, message: '请选择所属上级', trigger: 'change' }],
          status: [{ required: true, message: '选择用户状态', trigger: 'change' }],
          is_can_receive: [{ required: true, message: '选择是否有领取新资源的权限', trigger: 'change' }],
          receive_is_need_ts: [{ required: true, message: '选择此用户是否限制通时', trigger: 'change' }],
          receive_is_need_wx: [{ required: true, message: '请选择此用户是否限制微信添加数', trigger: 'change' }],
          role: [{ required: true, message: '请选择此用户的角色', trigger: 'change' }]
        },
        uid: '',
        parent: '',
        statusVisible: false,
        memberStatus: '',
        memberStatusOpts: {},
        groupTypeOpts: {},
        selectedRowKeys: [],
        batchVisible: false,
        batchForm: {},
        batchRules: {
          resource_daily_num_limit: [{ required: true, message: '必须设置每天初始资源数', trigger: 'blur' }],
          target_currmonth_yj: [{ required: true, message: '必须设置当月业绩目标', trigger: 'blur' }],
          target_dacall_sc: [{ required: true, message: '必须设置每天电话目标', trigger: 'blur' }]
        },
        createValue: []
      }
    },
    created () {
      this.queryParam['filter[tab]'] = 10
    },
    computed: {
      rowSelection () {
        return {
          onChange: this.onSelectChange,
          getCheckboxProps: record => ({
            props: {
              disabled: record.lvl === '1', // Column configuration not to be checked
              name: record.name
            }
          })
        }
      }
    },
    methods: {
      handleRange (selectedKeys, confirm, dataIndex) {
        confirm()
        this.searchText = selectedKeys[0]
        this.searchedColumn = dataIndex
        this.$refs.table.refresh(true)
      },
      rangeReset (clearFilters) {
        clearFilters()
        this.createValue = []
        delete this.queryParam['filter[begin_hiredate_time]']
        delete this.queryParam['filter[end_hiredate_time]']
        this.$refs.table.refresh(true)
      },
      batchSet () {
        getMemberSetting().then(res => {
          if (res.status === 0) {
            this.batchVisible = true
          } else {
            this.$warning({
              title: res.msg
            })
          }
        })
      },
      onChange (date, dateString) {
        this.createValue = date
        this.queryParam['filter[begin_hiredate_time]'] = dateString[0]
        this.queryParam['filter[end_hiredate_time]'] = dateString[1]
      },
      editStatus (uid, parent) {
        const app = this
        getMemberStatus(uid).then(res => {
          if (res.status === 0) {
            app.memberStatusOpts = res.result.items
            app.uid = uid
            app.parent = parent
            app.memberStatus = res.result.selection
            app.statusVisible = true
          } else {
            app.$warning({
              title: res.msg
            })
          }
        })
      },
      handleSelect (selectedKeys, confirm, dataIndex) {
        confirm()
        this.searchText = selectedKeys[0]
        this.searchedColumn = dataIndex
        this.queryParam['filter[' + dataIndex + ']'] = selectedKeys[0]
      },
      handleReset (clearFilters, dataIndex) {
        clearFilters()
        delete this.queryParam['filter[' + dataIndex + ']']
      },
      submitStatus () {
        const app = this
        const data = {}
        data['user[work_status]'] = app.memberStatus
        data['user[parent_id]'] = app.parent
        postMemberStatus(app.uid, data).then(res => {
          if (res.status === 0) {
            app.statusVisible = false
            app.$refs.table.refresh()
          } else {
            app.$warning({
              title: res.msg
            })
          }
        })
      },
      onSubmit () {
        const app = this
        const data = {}
        app.$refs.editForm.validate(valid => {
          if (valid) {
            for (const k in app.editForm) {
              data['user[' + k + ']'] = app.editForm[k]
            }
            postEditMember(app.uid, data).then(res => {
              if (res.status === 0) {
                app.resetForm()
                app.editVisible = false
                app.$refs.table.refresh()
              } else {
                app.$warning({
                  title: res.msg
                })
              }
            })
          } else {
            return false
          }
        })
      },
      resetForm () {
        this.$refs.editForm.resetFields()
      },
      editMember (uid) {
        const app = this
        getEditMember(uid).then(res => {
          if (res.status === 0) {
            app.groupOpts = res.result.group_opts
            app.roleOpts = res.result.role_opts
            app.userOpts = res.result.user_opts
            app.ynOpts = res.result.yn_opts
            app.statusOpts = res.result.status_opts
            app.groupTypeOpts = res.result.group_type_opts
            app.editForm = res.result.user
            app.uid = uid
            app.editVisible = true
          }
        })
      },
      saveSetting (uid, num, yj, call) {
        const app = this
        const { resourcesForm, monthYjForm, callForm } = this
        const data = {}
        data['user_info[uid]'] = uid
        if (resourcesForm['num' + uid] !== num) {
          data['user_info[resource_daily_num_limit]'] = resourcesForm['num' + uid]
          saveResources(data).then(res => {
            if (res.status === 0) {
              app.$refs.table.refresh()
            } else {
              app.$warning({
                title: res.msg
              })
            }
          })
        }
        if (monthYjForm['yj' + uid] !== yj) {
          data['user_info[target_currmonth_yj]'] = monthYjForm['yj' + uid]
          saveMonthYj(data).then(res => {
            if (res.status === 0) {
              app.$refs.table.refresh()
            } else {
              app.$warning({
                title: res.msg
              })
            }
          })
        }
        if (callForm['call' + uid] !== call) {
          data['user_info[target_dacall_sc]'] = callForm['call' + uid]
          saveCall(data).then(res => {
            if (res.status === 0) {
              app.$refs.table.refresh()
            } else {
              app.$warning({
                title: res.msg
              })
            }
          })
        }
      },
      onSelectChange (selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys
      },
      onBatch () {
        const app = this
        app.$refs.batchForm.validate(valid => {
          if (valid) {
            const form = {}
            form['user_info[uid]'] = app.selectedRowKeys
            for (const k in app.batchForm) {
              form['user_info[' + k + ']'] = app.batchForm[k]
            }
            postMemberSetting(form).then(res => {
              if (res.status === 0) {
                app.batchVisible = false
                app.$refs.table.refresh()
              } else {
                app.$warning({
                  title: res.msg
                })
              }
            })
          } else {
            return false
          }
        })
      },
      filterOption (input, option) {
        return (option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0)
      }
    }
  }
</script>

<style scoped>

</style>
